<template>
	<view class="app-container">
		<!-- 登录页面 -->
		<view v-if="currentPage === 'login'" class="login-container">
			<view class="login-card">
				<view class="login-title">用户登陆</view>

				<view class="form-group">
					<input type="text" class="form-input" placeholder="请输入用户名"
						:class="{ 'has-error': errorMsg.username }" v-model="formData.username" />
					<view class="error-message" v-if="errorMsg.username">{{ errorMsg.username }}</view>
				</view>

				<view class="form-group">
					<view class="password-input-wrapper">
						<input :type="passwordVisible ? 'text' : 'password'" class="form-input" placeholder="请输入密码"
							:class="{ 'has-error': errorMsg.password }" v-model="formData.password" />
						<view class="password-toggle" @click="togglePasswordVisibility">
							<text class="iconfont">{{ passwordVisible ? '&#xe646;' : '&#xe645;' }}</text>
						</view>
					</view>
					<view class="error-message" v-if="errorMsg.password">{{ errorMsg.password }}</view>
				</view>

				<button class="login-button" :disabled="isLoading || !isFormValid" @click="handleLogin">
					{{ isLoading ? '登录中...' : '登录' }}
				</button>

				<view class="register-link" @tap="toRegister">
					还没有账号？<text class="register-text">立即注册</text>
				</view>
			</view>
		</view>

		<!-- 注册页面 -->
		<view v-else-if="currentPage === 'register'" class="register-container">
			<view class="register-card">
				<view class="register-title">用户注册</view>

				<view class="form-group">
					<input type="text" class="form-input" placeholder="请输入用户名"
						:class="{ 'has-error': registerError.username }" v-model="registerData.username" />
					<view class="error-message" v-if="registerError.username">{{ registerError.username }}</view>
				</view>

				<view class="form-group">
					<input type="password" class="form-input" placeholder="请输入密码"
						:class="{ 'has-error': registerError.password }" v-model="registerData.password" />
					<view class="error-message" v-if="registerError.password">{{ registerError.password }}</view>
				</view>

				<view class="form-group">
					<input type="password" class="form-input" placeholder="请再次输入密码"
						:class="{ 'has-error': registerError.confirmPassword }"
						v-model="registerData.confirmPassword" />
					<view class="error-message" v-if="registerError.confirmPassword">{{ registerError.confirmPassword }}
					</view>
				</view>

				<button class="register-button" :disabled="isRegistering || !isRegisterFormValid"
					@click="handleRegister">
					{{ isRegistering ? '注册中...' : '注册' }}
				</button>

				<view class="login-link" @tap="toLogin">
					已有账号？<text class="login-text">立即登录</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'AuthPages',
		data() {
			return {
				currentPage: 'login', // 当前显示的页面：login 或 register
				formData: {
					username: '',
					password: ''
				},
				registerData: {
					username: '',
					password: '',
					confirmPassword: ''
				},
				passwordVisible: false,
				errorMsg: {
					username: '',
					password: ''
				},
				registerError: {
					username: '',
					password: '',
					confirmPassword: ''
				},
				isLoading: false,
				isRegistering: false
			}
		},
		computed: {
			isFormValid() {
				return this.formData.username && this.formData.password
			},
			isRegisterFormValid() {
				return (
					this.registerData.username &&
					this.registerData.password &&
					this.registerData.password === this.registerData.confirmPassword
				)
			}
		},
		methods: {
			// 登录相关方法
			togglePasswordVisibility() {
				this.passwordVisible = !this.passwordVisible
			},
			validateLoginForm() {
				this.errorMsg = {
					username: this.formData.username ? '' : '请输入用户名',
					password: this.formData.password ? '' : '请输入密码'
				}
				return Object.values(this.errorMsg).every(msg => !msg)
			},
		async handleLogin() {
		  if (!this.validateLoginForm()) return // 表单校验
		
		  this.isLoading = true // 显示加载状态
		  this.errorMsg = {} // 清空错误信息
		
		  try {
		    // 调用自定义云函数（非 uni-id，需自行实现后端）
		    const result = await uniCloud.callFunction({
		      name: 'user-auth', // 云函数名称（需与后端一致）
		      data: {
		        action: 'login', // 操作类型
		        username: this.formData.username.trim(), // 去除首尾空格
		        password: this.formData.password // 原始密码（后端需加密验证）
		      },
		      timeout: 10000 // 超时时间（10秒）
		    })
		
		    // 处理返回结果
		    if (result.result.code === 200) {
		      // 登录成功
		      uni.showToast({
		        title: '登录成功',
		        icon: 'none',
		        duration: 1500
		      })
		
		      // 存储用户信息和 Token
		      uni.setStorageSync('token', result.result.token)
		      uni.setStorageSync('userInfo', result.result.userInfo)
		
		      // 跳转至首页（根据实际路由修改）
		      uni.switchTab({
		        url: '/pages/index/index'
		      })
		    } else {
		      // 登录失败提示
		      uni.showToast({
		        title: result.result.msg || '登录失败，请检查用户名或密码',
		        icon: 'none',
		        duration: 2000
		      })
		    }
		  } catch (error) {
		    // 网络错误处理
		    console.error('登录请求失败:', error)
		    uni.showToast({
		      title: '网络请求失败，请重试',
		      icon: 'none'
		    })
		  } finally {
		    this.isLoading = false // 隐藏加载状态
		  }
		},

			// 注册相关方法
			validateRegisterForm() {
				const errors = {
					username: '',
					password: '',
					confirmPassword: ''
				}

				if (!this.registerData.username) {
					errors.username = '请输入用户名'
				} else if (this.registerData.username.length < 3) {
					errors.username = '用户名长度至少为3个字符'
				}

				if (!this.registerData.password) {
					errors.password = '请输入密码'
				} else if (this.registerData.password.length < 6) {
					errors.password = '密码长度至少为6个字符'
				}

				if (!this.registerData.confirmPassword) {
					errors.confirmPassword = '请确认密码'
				} else if (this.registerData.confirmPassword !== this.registerData.password) {
					errors.confirmPassword = '两次输入的密码不一致'
				}

				this.registerError = errors
				return Object.values(errors).every(msg => !msg)
			},
			async handleRegister() {
			  if (!this.validateRegisterForm()) return; // 前端校验
			
			  this.isRegistering = true;
			  this.registerError = {};
			
			  try {
			    const result = await uniCloud.callFunction({
			      name: 'user-auth',
			      data: {
			        action: 'register',
			        username: this.registerData.username.trim(),
			        password: this.registerData.password,
			        confirmPassword: this.registerData.confirmPassword
			      }
			    });
			
			    if (result.result.code === 201) {
			      uni.showToast({
			        title: '注册成功，即将跳转登录页',
			        icon: 'none',
			        duration: 1500
			      });
			      // 自动跳转登录页
			      setTimeout(() => {
			        this.toLogin(); // 调用页面切换方法
			      }, 1500);
			    } else if (result.result.code === 400) {
			      // 注册参数错误
			      uni.showToast({
			        title: result.result.msg,
			        icon: 'none',
			        duration: 2000
			      });
			    } else if (result.result.code === 409) {
			      // 用户名重复
			      this.registerError.username = result.result.msg; // 显示错误信息
			    } else {
			      uni.showToast({
			        title: result.result.msg || '注册失败，请重试',
			        icon: 'none',
			        duration: 2000
			      });
			    }
			  } catch (error) {
			    console.error('注册请求失败:', error);
			    uni.showToast({ title: '网络错误', icon: 'none' });
			  } finally {
			    this.isRegistering = false;
			  }
			},
			// 页面切换方法
			toRegister() {
				this.currentPage = 'register'
				// 重置注册表单
				this.registerData = {
					username: '',
					password: '',
					confirmPassword: ''
				}
				this.registerError = {
					username: '',
					password: '',
					confirmPassword: ''
				}
			},
			toLogin() {
				this.currentPage = 'login'
				// 重置登录表单
				this.formData = {
					username: '',
					password: ''
				}
				this.errorMsg = {
					username: '',
					password: ''
				}
			}
		}
	}
</script>

<style>
	/* 基础样式 */
	.app-container {
		min-height: 100vh;
		background-color: #f5f7fa;
	}

	/* 登录页面样式 */
	.login-container {
		display: flex;
		justify-content: center;
		align-items: center;
		min-height: 100vh;
		padding: 0 1rem;
	}

	.login-card {
		width: 100%;
		max-width: 320px;
		padding: 1.5rem;
		background-color: #ffffff;
		border-radius: 0.5rem;
		box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
	}

	.login-title {
		margin-bottom: 1.5rem;
		font-size: 1.25rem;
		font-weight: 600;
		text-align: center;
		color: #1f2937;
	}

	.form-group {
		margin-bottom: 1rem;
	}

	.form-input {
		width: 100%;
		height: 2.5rem;
		padding: 0 0.75rem;
		border: 1px solid #e5e7eb;
		border-radius: 0.375rem;
		background-color: #ffffff;
		font-size: 1rem;
		color: #1f2937;
		transition: all 0.2s ease;
		box-sizing: border-box;
	}

	.form-input:focus {
		outline: none;
		border-color: #3b82f6;
		box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.3);
	}

	.form-input.has-error {
		border-color: #ef4444;
	}

	.password-input-wrapper {
		position: relative;
	}

	.password-toggle {
		position: absolute;
		right: 0.75rem;
		top: 50%;
		transform: translateY(-50%);
		color: #9ca3af;
		cursor: pointer;
	}

	.error-message {
		margin-top: 0.25rem;
		font-size: 0.875rem;
		color: #ef4444;
	}

	.login-button {
		width: 100%;
		height: 2.5rem;
		margin-top: 0.5rem;
		background-color: #3b82f6;
		border-radius: 0.375rem;
		color: #ffffff;
		font-size: 1rem;
		font-weight: 500;
		cursor: pointer;
		transition: all 0.2s ease;
		border: none;
	}

	.login-button:disabled {
		background-color: #94a3b8;
		cursor: not-allowed;
	}

	.login-button:not(:disabled):hover {
		background-color: #2563eb;
	}

	.login-button:not(:disabled):active {
		background-color: #1d4ed8;
	}

	.register-link {
		margin-top: 1rem;
		text-align: center;
		font-size: 0.875rem;
		color: #6b7280;
	}

	.register-text {
		color: #3b82f6;
		text-decoration: underline;
		cursor: pointer;
	}

	/* 注册页面样式 */
	.register-container {
		display: flex;
		justify-content: center;
		align-items: center;
		min-height: 100vh;
		padding: 0 1rem;
	}

	.register-card {
		width: 100%;
		max-width: 320px;
		padding: 1.5rem;
		background-color: #ffffff;
		border-radius: 0.5rem;
		box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
	}

	.register-title {
		margin-bottom: 1.5rem;
		font-size: 1.25rem;
		font-weight: 600;
		text-align: center;
		color: #1f2937;
	}

	.register-button {
		width: 100%;
		height: 2.5rem;
		margin-top: 0.5rem;
		background-color: #10b981;
		border-radius: 0.375rem;
		color: #ffffff;
		font-size: 1rem;
		font-weight: 500;
		cursor: pointer;
		transition: all 0.2s ease;
		border: none;
	}

	.register-button:disabled {
		background-color: #94a3b8;
		cursor: not-allowed;
	}

	.register-button:not(:disabled):hover {
		background-color: #059669;
	}

	.register-button:not(:disabled):active {
		background-color: #047857;
	}

	.login-link {
		margin-top: 1rem;
		text-align: center;
		font-size: 0.875rem;
		color: #6b7280;
	}

	.login-text {
		color: #3b82f6;
		text-decoration: underline;
		cursor: pointer;
	}
</style>